const express = require('express');
const router = express.Router();
const { pool } = require('../database/connection');

// 获取赛事列表数据
router.get('/list', async (req, res) => {
  try {
    const { 
      page = 1, 
      limit = 10, 
      tournament_name, 
      tournament_intro, 
      tournament_score,
      remarks,
      tournament_type,
      status,
      start_date,
      end_date
    } = req.query;
    
    // 构建查询条件
    let whereConditions = [];
    let queryParams = [];
    
    if (tournament_name) {
      whereConditions.push('tournament_name LIKE ?');
      queryParams.push(`%${tournament_name}%`);
    }
    
    if (tournament_intro) {
      whereConditions.push('tournament_intro LIKE ?');
      queryParams.push(`%${tournament_intro}%`);
    }
    
    if (tournament_score) {
      whereConditions.push('tournament_score = ?');
      queryParams.push(tournament_score);
    }
    
    if (remarks) {
      whereConditions.push('remarks LIKE ?');
      queryParams.push(`%${remarks}%`);
    }
    
    if (tournament_type) {
      whereConditions.push('tournament_type = ?');
      queryParams.push(tournament_type);
    }
    
    if (status) {
      whereConditions.push('status = ?');
      queryParams.push(status);
    }
    
    if (start_date && end_date) {
      whereConditions.push('match_time BETWEEN ? AND ?');
      queryParams.push(start_date, end_date);
    }
    
    const whereClause = whereConditions.length > 0 ? `WHERE ${whereConditions.join(' AND ')}` : '';
    
    // 计算分页
    const offset = (page - 1) * limit;
    
    // 查询总数
    const countQuery = `SELECT COUNT(*) as total FROM matches ${whereClause}`;
    const [countResult] = await pool.query(countQuery, queryParams);
    const total = countResult[0].total;
    
    // 查询数据
    const dataQuery = `
      SELECT 
        id,
        tournament_name,
        tournament_type,
        tournament_score,
        tournament_intro,
        venue,
        match_time,
        status,
        remarks,
        created_at,
        updated_at
      FROM matches 
      ${whereClause}
      ORDER BY match_time DESC 
      LIMIT ? OFFSET ?
    `;
    
    const [rows] = await pool.query(dataQuery, [...queryParams, parseInt(limit), parseInt(offset)]);
    
    res.json({
      success: true,
      data: {
        list: rows,
        pagination: {
          current: parseInt(page),
          pageSize: parseInt(limit),
          total: total,
          pages: Math.ceil(total / limit)
        }
      },
      message: '获取数据成功'
    });
    
  } catch (error) {
    console.error('获取赛事列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取数据失败',
      error: error.message
    });
  }
});

// 获取单个赛事详情
router.get('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    
    const query = `
      SELECT 
        id,
        tournament_name,
        tournament_type,
        tournament_score,
        tournament_intro,
        venue,
        match_time,
        status,
        remarks,
        created_at,
        updated_at
      FROM matches 
      WHERE id = ?
    `;
    
    const [rows] = await pool.execute(query, [id]);
    
    if (rows.length === 0) {
      return res.status(404).json({
        success: false,
        message: '未找到该赛事数据'
      });
    }
    
    res.json({
      success: true,
      data: rows[0],
      message: '获取数据成功'
    });
    
  } catch (error) {
    console.error('获取赛事详情失败:', error);
    res.status(500).json({
      success: false,
      message: '获取数据失败',
      error: error.message
    });
  }
});

// 添加新赛事
router.post('/', async (req, res) => {
  try {
    const { 
      tournament_name, 
      tournament_type, 
      tournament_score, 
      tournament_intro, 
      venue,
      match_time, 
      status, 
      remarks 
    } = req.body;
    
    if (!tournament_name || !venue || !match_time) {
      return res.status(400).json({
        success: false,
        message: '缺少必填字段'
      });
    }
    
    const query = `
      INSERT INTO matches (
        tournament_name, tournament_type, tournament_score, tournament_intro,
        venue, match_time, status, remarks
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    `;
    
    const [result] = await pool.execute(query, [
      tournament_name, tournament_type || '常规赛', tournament_score || 0, tournament_intro || '',
      venue, match_time, status || 'pending', remarks || ''
    ]);
    
    res.json({
      success: true,
      data: { id: result.insertId },
      message: '添加成功'
    });
    
  } catch (error) {
    console.error('添加赛事失败:', error);
    res.status(500).json({
      success: false,
      message: '添加失败',
      error: error.message
    });
  }
});

// 更新赛事
router.put('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const { 
      tournament_name, 
      tournament_type, 
      tournament_score, 
      tournament_intro, 
      venue,
      match_time, 
      status, 
      remarks 
    } = req.body;
    
    const query = `
      UPDATE matches 
      SET tournament_name = ?, tournament_type = ?, tournament_score = ?, tournament_intro = ?,
          venue = ?, match_time = ?, status = ?, remarks = ?
      WHERE id = ?
    `;
    
    const [result] = await pool.execute(query, [
      tournament_name, tournament_type, tournament_score, tournament_intro,
      venue, match_time, status, remarks, id
    ]);
    
    if (result.affectedRows === 0) {
      return res.status(404).json({
        success: false,
        message: '未找到该赛事数据'
      });
    }
    
    res.json({
      success: true,
      message: '更新成功'
    });
    
  } catch (error) {
    console.error('更新赛事失败:', error);
    res.status(500).json({
      success: false,
      message: '更新失败',
      error: error.message
    });
  }
});

// 删除赛事
router.delete('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    
    const query = 'DELETE FROM matches WHERE id = ?';
    const [result] = await pool.execute(query, [id]);
    
    if (result.affectedRows === 0) {
      return res.status(404).json({
        success: false,
        message: '未找到该赛事数据'
      });
    }
    
    res.json({
      success: true,
      message: '删除成功'
    });
    
  } catch (error) {
    console.error('删除赛事失败:', error);
    res.status(500).json({
      success: false,
      message: '删除失败',
      error: error.message
    });
  }
});

// 批量删除赛事
router.delete('/batch', async (req, res) => {
  try {
    const { ids } = req.body;
    
    if (!ids || !Array.isArray(ids) || ids.length === 0) {
      return res.status(400).json({
        success: false,
        message: '请提供要删除的赛事ID列表'
      });
    }
    
    const placeholders = ids.map(() => '?').join(',');
    const query = `DELETE FROM matches WHERE id IN (${placeholders})`;
    
    const [result] = await pool.execute(query, ids);
    
    res.json({
      success: true,
      data: { deletedCount: result.affectedRows },
      message: `成功删除 ${result.affectedRows} 条赛事数据`
    });
    
  } catch (error) {
    console.error('批量删除赛事失败:', error);
    res.status(500).json({
      success: false,
      message: '批量删除失败',
      error: error.message
    });
  }
});

module.exports = router;
